package com.xsjl.manage.zuulFilter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xsjl.common.entity.Result;
import com.xsjl.common.entity.StatusCode;
import com.xsjl.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class WebFilter extends ZuulFilter {

    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private JwtUtil jwtUtil;
    @Override
    public String filterType() {
        //过滤器类型
        //在请求到达网关的时候，网关路由执行之前执行
        // 前置过滤器
        //        return "pre";
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
         //过滤器是一个链条，也称之为过滤器栈，执行顺序是按照该方法的返回值判断的
        return 0;// 优先级为0，数字越大，优先级越低
    }

    @Override
    public boolean shouldFilter() {
        //当前过滤器是否启用的开关，如果是true，则启用，false代表不启用。
        return true;// 是否执行该过滤器，此处为true，说明需要过滤
    }

    @Override
    public Object run() throws ZuulException {

        System.out.println("web后台网关..zuul前置过滤器");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //处理CORS跨域请求，因为跨域请求的第一次请求是预请求，不带头信息的，因此要过滤掉
        if (request.getMethod().equals("OPTIONS")) {
            return null;
        }
        String url = request.getRequestURL().toString();
        if (url.contains("/admin/login")) {
            System.out.println("登陆页面" + url);
            return null;
        }
        String authrization = request.getHeader("Authorization");
        if (authrization != null && authrization.startsWith("Bearer ")) {
            String token = authrization.substring(7);
            Claims claims = jwtUtil.parseJWT(token);
            String role = (String) claims.get("roles");
            if (claims != null && "admin".equals(role)) {
                currentContext.addZuulRequestHeader("Authorization", authrization);
                return null;
            }
        }
        // 不再向下跳转
        currentContext.setSendZuulResponse(false);
        // http响应码401(没有授权)或403（禁止访问）
        currentContext.setResponseStatusCode(401);
        Result result = new Result(false, StatusCode.ACCESSERROR, "你没有权限访问");
        String valueAsString = null;
        try {
            valueAsString = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        currentContext.setResponseBody(valueAsString);
        currentContext.getResponse().setCharacterEncoding("utf-8");
        return null;

    }
}
